<template>
  <div class="ar-map-layer-content">
    <img class="close" @click="close" src="/images/new/mapclose.png" />
    <div
      class="high"
      @click="changeLevel('high')"
      :class="{ active: currentLevel == 'high' }"
    >
      高点
    </div>
    <div
      class="low"
      @click="changeLevel('low')"
      :class="{ active: currentLevel == 'low' }"
    >
      低点
    </div>
    <div ref="mapAr" id="mapAr"></div>
  </div>
</template>
  
  <script setup>
import "ol/ol.css";
import { ref, onMounted, defineComponent, defineEmits } from "vue";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import Feature from "ol/Feature";
import { LineString, Point, Polygon } from "ol/geom";
import { Icon, Style, Stroke, Circle, Fill, Text } from "ol/style";
import Overlay from "ol/Overlay.js";
import { Image as ImageLayer } from "ol/layer.js";
import ImageWMS from "ol/source/ImageWMS.js";
import VectorTileSource from "ol/source/VectorTile";
import VectorTileLayer from "ol/layer/VectorTile";
import MVT from "ol/format/MVT";
import { defaults } from "ol/interaction/defaults";
import PointerInteraction from "ol/interaction/Pointer";
import DragPan from "ol/interaction/DragPan";
const mapAr = ref(null);
const animating = ref(false);
let map;
let arrPoint = ref([]);
let polyonArr = ref([]);

const props = defineProps({
  vid: String,
});

const emit = defineEmits(["close", "changeGd"]);
const close = () => {
  emit("close");
};

// 添加蒙版图层
let vectorLayer = null;
let maskLayer = null;
let maskLayer1 = null;
const addLayer = () => {
  const innerRing2 = [
    [117.71999684330913, 39.00776477167736],
    [117.7318497047607, 39.003581408812096],
    [117.72435451296045, 38.991205627002365],
    [117.72296005867203, 38.99242577450473],
    [117.72069407045333, 38.991205627002365],
    [117.71964822973702, 38.99312300164895],
    [117.71407041258334, 38.99207716093263],
    [117.71180442436466, 38.99260008129079],
  ];

  const innerRing4 = [
    [117.73239413935512, 39.00355603914005],
    [117.7249117338587, 38.99037807125083],
    [117.7419984210371, 38.98445915347008],
    [117.7476939834299, 38.98658102965563],
    [117.74624217340819, 38.98222559959055],
    [117.75026257039136, 38.985575930409844],
    [117.75472967815041, 38.98367740961224],
    [117.7571865874179, 38.97831688030138],
    [117.75774497588779, 38.983119021142365],
    [117.76176537287094, 38.98155553342669],
    [117.76221208364684, 38.97708842566763],
    [117.76533905907819, 38.976530037197755],
    [117.76522738138421, 38.980103723405],
    [117.78644614323973, 38.97407312793027],
    [117.78879137481323, 38.97753513644354],
    [117.77963380390716, 38.985910963491776],
    [117.76254711672877, 39.044988463605314],
    [117.75975517437936, 39.04733369517882],
    [117.76198872825888, 39.05046067061016],
    [117.77393824151437, 39.04677530670894],
    [117.77628347308787, 39.05347596834752],
    [117.73875976791179, 39.062298506171665],
    [117.73697292480816, 39.05269422448969],
    [117.74702391726605, 39.047445372872794],
    [117.74211009873108, 39.035830892699245],
    [117.7462421734082, 39.034602438065505],
    [117.74546042955038, 39.03248056187995],
    [117.75283115735282, 39.02946526414259],
    [117.74903411575762, 39.02242956942207],
    [117.76165369517696, 39.01773910627506],
    [117.76835435681555, 38.99060142663878],
    [117.73328756090694, 39.00355603914005],
  ];

  const innerRing5 = [
    [117.69788, 38.961829, 0],
    [117.6955, 38.960479, 0],
    [117.692623, 38.958592, 0],
    [117.689583, 38.956108, 0],
    [117.701048, 38.949191, 0.5],
    [117.701458, 38.949774, 0],
    [117.701405, 38.95122, 0],
    [117.705146, 38.958996, 0],
    [117.705203, 38.95937, 0],
    [117.705216, 38.959658, 0.2],
    [117.702552, 38.960895, 0.3],
    [117.702059, 38.961107, 0.1],
    [117.701264, 38.961227, 0],
  ];

  // 创建多边形（带洞）
  const polygon1 = new Polygon([innerRing2]);
  const polygon2 = new Polygon([innerRing4]);
  const polygon3 = new Polygon([innerRing5]);
  // 创建一个矢量图层以显示蒙版
  maskLayer = new VectorLayer({
    source: new VectorSource({
      features: [
        // new Feature(polygon),
        new Feature(polygon1),
        new Feature(polygon2),
        new Feature(polygon3),
      ],
    }),
    style: new Style({
      fill: new Fill({
        color: "rgba(4,85,154,1)", // 蒙版颜色
        // color: pattern,
      }),
    }),
  });

  // 添加蒙版层到地图
  map.addLayer(maskLayer);
  map.render();
  maskLayer.setZIndex(2);

  // 添加遮罩
  // 创建遮罩层
  maskLayer1 = new VectorLayer({
    source: new VectorSource(),
    style: new Style({
      fill: new Fill({
        color: "rgba(17, 134, 216, 0.8)", // 半透明黑色遮罩
      }),
    }),
  });

  // 获取地图范围
  const mapExtent = map.getView().getProjection().getExtent();

  // 创建遮罩多边形
  const maskPolygon = new Polygon([
    [
      [mapExtent[0], mapExtent[1]],
      [mapExtent[2], mapExtent[1]],
      [mapExtent[2], mapExtent[3]],
      [mapExtent[0], mapExtent[3]],
      [mapExtent[0], mapExtent[1]],
    ],
  ]);

  // 将遮罩多边形添加到遮罩层
  const maskFeature = new Feature({
    geometry: maskPolygon,
  });
  maskLayer1.getSource().addFeature(maskFeature);
  // 将遮罩层添加到地图
  map.addLayer(maskLayer1);
  maskLayer1.setZIndex(1);
};

// 添加点位
let highLayer = null;
let lowLayer = null;
let allhighFectures = [];
let alllowFectures = [];
// 当前点位
let currentHigh = ref(null);
// 修改高低点
let currentLevel = ref("high");
const changeLevel = (level) => {
  currentLevel.value = level;
  if (level == "low") {
    deletemLayer();
    addlowLayer();
    if (highLayer) {
      highLayer.setVisible(false);
    }
    let view = map.getView();
    if (currentHigh.value.lng) {
      view.animate({
        center: [currentHigh.value.lng, currentHigh.value.lat],
        zoom: 14.7,
        duration: 1000,
      });
    }
  } else {
    let view = map.getView();
    view.animate({
      center: [117.74256851451989, 39.00380206757584],
      zoom: 11.7,
      duration: 1000,
    });
    addLayer();
    if (highLayer) {
      highLayer.setVisible(true);
    }
    if (lowLayer) {
      map.getLayers().remove(lowLayer);
      lowLayer = null;
    }
  }
};

let gdList = ref([]);
// 获取高点设备
const getData = () => {
  useApi.post("/dynamicview/ar/highandlows", {}).then((res) => {
    gdList.value = res.data.highList;
    addhightLayer();
  });
};

// 添加高点设备
const addhightLayer = async () => {
  if (!map) return;
  let brr = [];
  let arr = gdList.value;
  // 1、初始化点位的图层
  highLayer = new VectorLayer({
    source: new VectorSource(),
  });
  allhighFectures = [];
  for (let i = 0; i < arr.length; i++) {
    // 2、创建点位的feature
    let feature = new Feature({
      geometry: new Point([arr[i].lng, arr[i].lat]),
      attrs: {
        // type: "point",
        // name: "点位1",
        // url: "http://10.198.12.12.m3u8",
        ...arr[i],
        high: true,
      },
      draggable: false,
    });

    feature.setStyle(
      new Style({
        image: new Icon({
          src:
            props.vid == arr[i].cameraId
              ? "/images/new/high.png"
              : "/images/new/lowicon.png",
          width: 42,
          height: 42,
        }),
        text: new Text({
          text: arr[i].deviceCount, // 从要素属性中获取文本
          font: "12px Arial", // 字体样式
          fill: new Fill({ color: "#fff" }), // 文本填充颜色
          offsetX: 0, // 水平偏移
          offsetY: 1, // 垂直偏移
          textAlign: "center", // 文本对齐方式
          textBaseline: "center", // 文本基线
        }),
      })
    );
    allhighFectures.push(feature);
  }

  // 3 、 将feature添加到layer中
  highLayer.getSource().addFeatures(allhighFectures);

  // 4、将feauture添加到layser

  map.addLayer(highLayer);
  highLayer.setZIndex(9);
  changeHighBg({
    cameraId: props.vid,
  });
};

// 添加低点设备
const addlowLayer = () => {
  // let arr = [
  //   {
  //     code: "11",
  //     name: "点位11",
  //     num: "1",
  //     center: [117.70452732437977, 39.01415772489177],
  //   },

  //   {
  //     code: "21",
  //     name: "点位21",
  //     num: "2",
  //     center: [117.70621804394155, 38.9904876510268],
  //   },
  // ];
  let arr = [];
  if (currentHigh.value.lowList) {
    arr = currentHigh.value.lowList;
  } else {
    arr = gdList.value.filter(
      (item) => item.cameraId == currentHigh.value.cameraId
    )[0].lowList;
  }
  // 1、初始化点位的图层
  if (!lowLayer) {
    lowLayer = new VectorLayer({
      source: new VectorSource(),
    });
  }
  alllowFectures = [];

  for (let i = 0; i < arr.length; i++) {
    // 2、创建点位的feature
    // if (!arr[i].lng) return
    let feature = new Feature({
      geometry: new Point([arr[i].lng, arr[i].lat]),
      attrs: {
        // type: "point",
        // name: "点位1",
        // url: "http://10.198.12.12.m3u8",
        ...arr[i],
        high: false,
      },
      draggable: false,
    });

    feature.setStyle(
      new Style({
        image: new Icon({
          src: "/images/new/lowicon.png",
          width: 42,
          height: 42,
        }),
        text: new Text({
          text: i, // 从要素属性中获取文本
          font: "12px Arial", // 字体样式
          fill: new Fill({ color: "#fff" }), // 文本填充颜色
          offsetX: 0, // 水平偏移
          offsetY: 1, // 垂直偏移
          textAlign: "center", // 文本对齐方式
          textBaseline: "center", // 文本基线
        }),
      })
    );
    alllowFectures.push(feature);
  }

  // 3 、 将feature添加到layer中
  lowLayer.getSource().addFeatures(alllowFectures);

  // 4、将feauture添加到layser

  map.addLayer(lowLayer);
  lowLayer.setZIndex(9);
};
// 修改选中状态

const changeHighBg = (data) => {
  currentHigh.value = data;
  let emitvalue = JSON.parse(JSON.stringify(data));
  delete emitvalue.lowList;
  emit("changeGd", emitvalue);
  // emit("changeGd", data);
  for (let i = 0; i < allhighFectures.length; i++) {
    let attrs = allhighFectures[i].get("attrs");
    if (data.cameraId === attrs.cameraId) {
      allhighFectures[i].setStyle(
        new Style({
          image: new Icon({
            src: "/images/new/high.png",
            width: 42,
            height: 42,
          }),
          text: new Text({
            text: attrs.deviceCount, // 从要素属性中获取文本
            font: "12px Arial", // 字体样式
            fill: new Fill({ color: "#fff" }), // 文本填充颜色
            offsetX: 0, // ���平偏移
            offsetY: 1, // ��直偏移
            textAlign: "center", // 文本对齐方式
            textBaseline: "center", // 文本基线
          }),
        })
      );
    } else {
      allhighFectures[i].setStyle(
        new Style({
          image: new Icon({
            src: "/images/new/lowicon.png",
            width: 42,
            height: 42,
          }),
          text: new Text({
            text: attrs.deviceCount, // 从要素属性中获取文本
            font: "12px Arial", // 字体样式
            fill: new Fill({ color: "#fff" }), // 文本填充颜色
            offsetX: 0, // ���平偏移
            offsetY: 1, // ��直偏移
            textAlign: "center", // 文本对齐方式
            textBaseline: "center", // 文本基线
          }),
        })
      );
    }
  }
};

// 删除遮罩图层
const deletemLayer = () => {
  if (maskLayer && maskLayer1) {
    map.getLayers().remove(maskLayer);
    map.getLayers().remove(maskLayer1);
    maskLayer = null;
    maskLayer1 = null;
  }
};

watch(
  () => props.vid,
  (newval) => {
    if (newval) {
      changeHighBg({
        cameraId: newval,
      });
    }
  },
  {
    deep: true,
  }
);

onMounted(async () => {
  getData();
  map = new Map({
    layers: [
      new ImageLayer({
        source: new ImageWMS({
          url: "https://vp.bcdtech.cn:8787/geoserver/wms",
          params: { LAYERS: "tjxgblack", VERSION: "1.1.0" },
          ratio: 1,
          serverType: "geoserver",
        }),
      }),
    ],
    target: mapAr.value,
    view: new View({
      center: [117.461765, 38.844979],
      projection: "EPSG:4326",
      minZoom: 4,
      zoom: 11.7,
    }),
    interactions: defaults({
      doubleClickZoom: true,
    }),
  });
  // 监听地图的postrender事件
  map.once("postrender", (event) => {
    addLayer();
    addhightLayer();
  });
  // 地图注册点击事件
  map.on("click", (event) => {
    let point = event.coordinate;
    console.log(point);
    // 获取点击的要素
    const clickedFeature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
      return feature;
    });
    let data = clickedFeature.get("attrs");
    if (data && data.high) {
      changeHighBg(data);
    }
  });
});

const getView = () => {
  // localStorage.setItem("polython", JSON.stringify(polyonArr.value));
  // return;
  let view = map.getView();
  let center = view.getCenter();
  console.log(center);
  console.log(view);
  center[0] = center[0] - 1;
  center[1] = center[1] - 1;
  view.setCenter(center);
  map.render();

  view.animate({
    center: [114.28, 34.54],
    zoom: 7,
    duration: 1000,
  });

  // 获取图层方法:等等
  // map.getLayers().item[1].getSource().on('click')
};

const setPolyon = () => {
  // 创建一个多边形要素的数据集，假设每个多边形有一个高度属性
  var features = [
    new Feature({
      geometry: new Polygon([
        [
          [117.69513238288741, 39.015957906515624],
          [117.69335591431309, 39.013219184130215],
          [117.69772306622495, 39.01114663746018],
          [117.69986963241892, 39.01462555508489],
        ],
      ]),
      height: 20,
    }),
    new Feature({
      geometry: new Polygon([
        [
          [117.69513238288741, 39.015957906515624],
          [117.69335591431309, 39.013219184130215],
          [117.69772306622495, 39.01114663746018],
          [117.69986963241892, 39.01462555508489],
        ],
      ]),
      height: 10,
    }),
  ];

  // 创建样式函数，根据每个面数据的高度进行样式设置
  var styleFunction = function (feature) {
    alert(1);
    var height = feature.get("height"); // 获取每个面数据的高度
    var color = height > 15 ? "rgba(255, 0, 0, 0.8)" : "rgba(0, 0, 255, 0.8)";

    return new Style({
      fill: new Fill({
        color: color,
      }),
      stroke: Stroke({
        color: "black",
        width: 2,
      }),
    });
  };

  // 创建 VectorSource 和 VectorLayer
  var vectorSource = new VectorSource({
    features: features,
  });
  var vectorLayer = new VectorLayer({
    source: vectorSource,
    style: function (feature) {
      console.log(feature);
      // 获取要素的属性
      var height = feature.get("height");

      // 根据属性值返回不同的样式
      var color = height > 15 ? "rgba(255, 0, 0, 0.8)" : "rgba(0, 0, 255, 0.8)";

      return new ol.style.Style({
        fill: new ol.style.Fill({
          color: color, // 填充颜色根据高度变化
        }),
        stroke: new ol.style.Stroke({
          color: "black",
          width: 2,
        }),
      });
    },
  });
  // debugger;
  // 添加 VectorLayer 到地图
  map.addLayer(vectorLayer);
  map.render();
};
</script>
  
<style lang="scss" scoped>
.ar-map-layer-content {
  width: 517px;
  height: 517px;
  background: url("/images/new/mapbg.png");
  background-size: contain;
  padding: 91px 117px 93px 68px;
  #mapAr {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: url("/images/new/mapbg.png");
    background-size: contain;
    overflow: hidden;
    opacity: 1;
  }
  .close {
    width: 55px;
    height: 55px;
    position: absolute;
    left: 262px;
    top: 0px;
    z-index: 999;
    cursor: pointer;
  }
  .high {
    position: absolute;
    left: 339px;
    top: 42px;
    width: 95px;
    height: 95px;
    background: url("/images/new/low.png") no-repeat;
    background-size: 100% 100%;
    text-align: center;
    line-height: 95px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 22.5px;
    color: #ffffff;
    z-index: 999;
    cursor: pointer;
    &.active {
      background: url("/images/new/high.png") no-repeat;
      background-size: 100% 100%;
    }
  }
  .low {
    width: 81.5px;
    height: 81.5px;
    position: absolute;
    right: 22px;
    top: 151px;
    background: url("/images/new/low.png") no-repeat;
    background-size: 100% 100%;
    text-align: center;
    line-height: 81.5px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 22.5px;
    color: #ffffff;
    z-index: 999;
    cursor: pointer;
    &.active {
      background: url("/images/new/high.png") no-repeat;
      background-size: 100% 100%;
    }
  }
}
</style>
  